#!/usr/bin/env node

import { existsSync, readFileSync } from 'fs'
import { join } from 'path'

console.log('🔍 验证构建结果...')

const distPath = join(process.cwd(), 'dist')

// 检查dist目录是否存在
if (!existsSync(distPath)) {
    console.error('❌ dist目录不存在，请先执行构建命令')
    process.exit(1)
}

// 检查关键文件
const requiredFiles = [
    'index.html',
    'assets',
    'js',
    'css'
]

let allFilesExist = true

requiredFiles.forEach(file => {
    const filePath = join(distPath, file)
    if (existsSync(filePath)) {
        console.log(`✅ ${file} 存在`)
    } else {
        console.log(`❌ ${file} 不存在`)
        allFilesExist = false
    }
})

// 检查index.html内容
const indexPath = join(distPath, 'index.html')
if (existsSync(indexPath)) {
    try {
        const content = readFileSync(indexPath, 'utf-8')
        if (content.includes('<div id="app"></div>')) {
            console.log('✅ index.html 内容正确')
        } else {
            console.log('❌ index.html 内容不正确')
            allFilesExist = false
        }

        // 检查是否有JavaScript引用
        if (content.includes('src=') && content.includes('.js')) {
            console.log('✅ JavaScript文件引用正确')
        } else {
            console.log('❌ JavaScript文件引用缺失')
            allFilesExist = false
        }

        // 检查是否有CSS引用
        if (content.includes('href=') && content.includes('.css')) {
            console.log('✅ CSS文件引用正确')
        } else {
            console.log('❌ CSS文件引用缺失')
            allFilesExist = false
        }

    } catch (error) {
        console.error('❌ 读取index.html失败:', error.message)
        allFilesExist = false
    }
}

// 检查assets目录结构
const assetsPath = join(distPath, 'assets')
if (existsSync(assetsPath)) {
    console.log('📁 assets目录结构:')
    try {
        const fs = await
        import ('fs')
        const files = fs.readdirSync(assetsPath, { recursive: true })
        files.forEach(file => {
            console.log(`  - ${file}`)
        })
    } catch (error) {
        console.log('  - 无法读取assets目录内容')
    }
}

if (allFilesExist) {
    console.log('\n🎉 构建验证通过！')
    console.log('🌐 可以使用以下命令预览: npm run preview')
} else {
    console.log('\n❌ 构建验证失败，请检查构建过程')
    process.exit(1)
}